package com.tsfyun.scm.config.ws;

import com.tsfyun.common.base.security.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;
import java.util.Objects;

@Slf4j
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse seHttpResponse,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if(serverHttpRequest instanceof ServletServerHttpRequest) {
            //前面已经根据token设置用户信息了
            Long personId = SecurityUtil.getCurrentPersonId();
            String userName = SecurityUtil.getCurrentPersonName();
            if(Objects.nonNull(personId)) {
                attributes.put("userId", Long.valueOf(personId));
                attributes.put("userName", userName);
                //从request里面获取对象，存放attributes
                return super.beforeHandshake(serverHttpRequest, seHttpResponse, wsHandler, attributes);
            }
            return false;
        } else {
            return false;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }



}
